/**
 * 程序起动初始化
 * @author keepsilent
 * @create 2016/03/23
 */

var webDevice = {};
var config = {};
webDevice.bindJpush = 0;
//webDevice.isApp = _is_app;
webDevice.networkType = '';

var serve_online = function() {
    config.serve(1);
}

var serve_offline = function() {
    config.serve(0);
}

/**
 * 初始化环境参数
 * @method webDevice.run
 */
webDevice.init = function() {
    webDevice.appEventListener();
    webDevice.weixinEventListener();
}

/**
 * 监听APP环境设置
 * @method webDevice.appEventListener
 */
webDevice.appEventListener = function() {
    if(webDevice.isApp == 0) {
        return false;
    }
    document.addEventListener("deviceready", webDevice.appDeviceReady, false);
    document.addEventListener("online", serve_online , false);
    document.addEventListener("offline", serve_offline , false);
    window.plugins.jPushPlugin.setApplicationIconBadgeNumber(0);
}

/**
 * APP设置准备就绪
 * @method webDevice.appDeviceReady
 */
webDevice.appDeviceReady = function() {
    webDevice.appJpushRun();
    webDevice.appGpsPosition();
}

/**
 * App 加载完成
 * @method webDevice.onload
 */
webDevice.onload = function() {
    webDevice.appUpdate();
}

/**
 * App 安桌升级
 * @method webDevice.appUpdate
 */
 webDevice.appUpdate = function() {
    if(config.appid != 3) {
         return false;
    }
    var url = "http://m.bingofresh.com/Public/Download/user.xml"
    window.AppUpdate.checkAppUpdate(function(){}, function(){}, url);
 }


/**
 * APP 安桌 GPS 定位
 * @method webDevice.appGpsPosition
 */
webDevice.appGpsPosition = function() {
    if(config.appid != 3) {
        return false;
    }
    var fun = function(){};
    window.plugins.locationService.getCurrentPosition(function(point){
        if(common.isOwnEmpty(point)) {
            return false;
        }
        _point = { longitude: point.coords.longitude ,latitude: point.coords.latitude};

        window.plugins.locationService.stop(fun(),fun());
    },function(e){
        window.plugins.locationService.stop(fun(),fun());
    });
}

/**
 * APP Jpush 运行
 * @method webDevice.appJpushRun
 */
webDevice.appJpushRun = function() {
    if( webDevice.bindJpush == 1) {
        return false;
    }
    if (window.plugins != undefined &&  window.plugins.jPushPlugin != undefined) {
        webDevice.bindJpush = 1;
        webDevice.JpushInit("messages",user.app_bingo_openid);
    }
}

/**
 *  Jpush 初始化
 *  @method webDevice.JpushInit
 *  @param {String} room 房间
 *  @param {String} bingo_openid 标识符
 */
webDevice.JpushInit = function(room, bingo_openid) {
    try {
        window.plugins.jPushPlugin.init();
        window.plugins.jPushPlugin.setTagsWithAlias([room], bingo_openid);
        if (device.platform != "Android") {
            window.plugins.jPushPlugin.setDebugModeFromIos();
            window.plugins.jPushPlugin.setApplicationIconBadgeNumber(0);
        } else {
            window.plugins.jPushPlugin.setDebugMode(true);
        }
        var onOpenNotification = function (event) { //应用没有打开状态
            try {
                var push_value, push_type, extrasContent;
                if (device.platform == "Android") {
                    extrasContent = window.plugins.jPushPlugin.openNotification.extras['cn.jpush.android.EXTRA'];
                    push_value = extrasContent.push_value;
                    push_type = extrasContent.push_type;
                } else {
                    push_value = event.push_value;
                    push_type = event.push_type;
                }
                if (push_value != undefined && push_type != undefined){
                    webDevice.JpushWork(push_type,push_value,0);
                }
            } catch (exception) {
                //console.log("JPushPlugin:onOpenNotification" + exception);
            }
        };
        var onReceiveNotification = function (event) {  //应用打开状态
            var push_value, push_type, extrasContent;
            try {
                if (device.platform == "Android") {
                    //var alertContent = window.plugins.jPushPlugin.receiveNotification.alert;
                    extrasContent = window.plugins.jPushPlugin.receiveNotification.extras['cn.jpush.android.EXTRA'];
                    push_value = extrasContent.push_value;
                    push_type = extrasContent.push_type;
                } else {
                    push_value = event.push_value;
                    push_type = event.push_type;
                }

                if (push_value != undefined && push_type != undefined){
                    webDevice.JpushWork(push_type,push_value,1);
                }
            } catch (exeption) {
                //console.log(exception)
            }
        };

        var onTagsWithAlias = function (event) {
            try {
                var result = "result code:" + event.resultCode + " ";
                result += "tags:" + event.tags + " ";
                result += "alias:" + event.alias + " ";
            } catch (exception) {
                //console.log(exception);
            }
        };
        document.addEventListener("jpush.setTagsWithAlias", onTagsWithAlias, false);
        document.addEventListener("jpush.openNotification", onOpenNotification, false);
        document.addEventListener("jpush.receiveNotification", onReceiveNotification, false);
    } catch (exception) {
        //console.log(exception);
    }
}


/**
 *  Jpush 事务
 *  @method webDevice.JpushWork
 *  @param {String} push_type 标识符
 *  @param {String} push_value 参数
 *  @param {String} status 状态,0:程序没有开启，1，程序开启
 */
webDevice.JpushWork = function(push_type, push_value, status) {
    if(status == 0) {
        app_cinfig.come_from = 'outside';
        window.location.href = '#/notice_list';
    } else {
        app_cinfig.come_from = 'inside';
        switch (push_type) {
            case 'Jpush_voucher_get': //领取代金券
                app_cinfig.voucherNews = 1;
                break;
        }
        app_cinfig.news = 1;
        notice.control('event');
    }
}

/**
 * 微信准备就绪
 * @method webDevice.appDeviceReady
 */
webDevice.weixinEventListener = function() {
    if(webDevice.isApp == 1) {
        return false;
    }

    wx.ready(function(){
        webDevice.getWeixinPositon();
        webDevice.getWeixinNetworkType();
    });

    webDevice.weixinShareInit();
}

/**
 * 获得微信网络类型
 * @method webDevice.getWeixinNetworkType
 */
webDevice.getWeixinNetworkType = function() {
    wx.getNetworkType({ success: function (result) {
        webDevice.networkType = result.networkType; // 返回网络类型2g，3g，4g，wifi
    }});
}
/**
 * 获得微信定位
 * @method webDevice.getWeixinPositon
 */
webDevice.getWeixinPositon = function() {
    if (config.isAppleDevice != 1) {
        return false;
    }

    // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
    wx.getLocation({
        type: 'wgs84', success: function (point) {
            _point = point;
        }
    });
}

/**
 * 微信分享初始货
 * @method webDevice.weixinShareInit
 */
webDevice.weixinShareInit = function() {
    wx.config({
        debug: false,
        appId: wxConfig.appId,
        timestamp: wxConfig.timestamp,
        nonceStr: wxConfig.nonceStr,
        signature: wxConfig.signature,
        jsApiList: [
            'onMenuShareTimeline',
            'onMenuShareAppMessage',
            'onMenuShareQQ',
            'onMenuShareWeibo',
            'showOptionMenu',
            'scanQRCode'
        ]
    });
    document.addEventListener("WeixinJSBridgeReady", webDevice.weixinShareEventListener, false);
}

/**
 * 微信分享事件临听
 * @method webDevice.weixinShareEventListener
 */
webDevice.weixinShareEventListener = function() {
    WeixinJSBridge.on('menu:share:appmessage', function (argv) {  //发送给好友
        WeixinJSBridge.invoke('sendAppMessage', {
            "appid": "",
            "img_url": share_info.img_url,
            "img_width": "104",
            "img_height": "99",
            "link": share_info.url,
            "desc": share_info.content,
            "title": share_info.title
        }, function (res) {
            common.share_url_record('share_friend', share_info.url);
            shareOrder.score_add();
        });
    });

    WeixinJSBridge.on('menu:share:timeline', function (argv) { //分享到朋友圈
        WeixinJSBridge.invoke('shareTimeline', {
            "img_url": share_info.img_url,
            "img_width": "104",
            "img_height": "99",
            "link": share_info.url,
            "desc": share_info.content,
            "title": share_info.title
        }, function (res) {
            common.share_url_record('share_group', share_info.url);
            shareOrder.score_add();
        });
    });

    WeixinJSBridge.on('menu:share:weibo', function (argv) { //分享到微博
        WeixinJSBridge.invoke('shareWeibo', {
            "content": share_info.content,
            "url": share_info.url
        }, function (res) {
            shareOrder.score_add();
        });
    });
}

webDevice.init();